package com.kamistoat.meimeichat.meimeichatclient.socket.handlers;

import com.alibaba.fastjson.JSON;
import com.kamistoat.meimeichat.meimeichatclient.application.UIServiceConnector;
import com.kamistoat.meimeichat.meimeichatclient.config.NettyClientConstant;
import com.kamistoat.meimeichat.meimeichatclient.infrastructure.util.BeanUtil;
import com.kamistoat.meimeichat.meimeichatclient.infrastructure.util.CacheUtil;
import com.kamistoat.meimeichat.meimeichatclient.socket.NettyClientBizHandler;
import com.kamistoat.meimeichat.meimeichatui.view.chat.IChatMethod;
import com.kamistoat.meimeichatserveraggrement.protocol.login.dto.ChatRecordDto;
import com.kamistoat.meimeichatserveraggrement.protocol.msg.MsgResponse;
import com.kamistoat.meimeichatserveraggrement.util.R;
import io.netty.channel.Channel;
import javafx.application.Platform;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;

/**
 * 客户端处理服务器返回的 私聊消息响应
 */
public class MsgHandler extends NettyClientBizHandler<MsgResponse> {

    public MsgHandler(UIServiceConnector uiServiceConnector) {
        super(uiServiceConnector);
    }

    /**
     * @param channel
     * @param msg
     * @Warning:子类只需要重写该方法
     */
    @Override
    public void channelRead(Channel channel, MsgResponse msg) {
        logger.info("收到好友 {} 经过服务器转发发送来的消息", msg.getSenderId());
        IChatMethod chat = uiServiceConnector.getIChatMethod();
        Platform.runLater(() -> {
            // 若当前并未与消息发送者建立对话框，则先展开其对话框
            if (!CacheUtil.talkMap.containsKey(msg.getSenderId())) {
                // 先展开对话框
                chat.addTalkBox(0, NettyClientConstant.TalkType.Friend.getCode(),
                        msg.getSenderId(), msg.getSenderNickname(), msg.getSenderHead(), "", msg.getMsgDate(), false);
                CacheUtil.talkMap.put(msg.getSenderId(), 1);
                // 发送web请求查询两者的旧聊天记录
                CloseableHttpClient httpClient = null;
                CloseableHttpResponse response = null;
                try {
                    httpClient = HttpClientBuilder.create().build();
                    URIBuilder uriBuilder = new URIBuilder(
                            NettyClientConstant.NETTY_SERVER_WEB_HOST +
                                    ":" +
                                    NettyClientConstant.NETTY_SERVER_WEB_PORT +
                                    NettyClientConstant.WebApi.QUERY_FRIEND_CHAT_RECORD.getUri());
                    uriBuilder.addParameter("userId", msg.getReceiverId());
                    uriBuilder.addParameter("talkId", msg.getSenderId());
                    uriBuilder.addParameter("msgDate", String.valueOf(msg.getMsgDate().getTime()));
                    HttpGet httpGet = new HttpGet(uriBuilder.build());
                    response = httpClient.execute(httpGet);
                    HttpEntity responseEntity = response.getEntity();
                    if (responseEntity != null) {
                        R responseR = JSON.parseObject(EntityUtils.toString(responseEntity), R.class);
                        if ((int) responseR.get("code") == 0 && JSON.parseArray(JSON.toJSONString(responseR.get("chatList")), ChatRecordDto.class).size() > 0) {
                            List<ChatRecordDto> chatRecordDtos = JSON.parseArray(JSON.toJSONString(responseR.get("chatList")), ChatRecordDto.class);
                            // 填充聊天信息
                            for (int i = chatRecordDtos.size() - 1; i >= 0; i--) {
                                ChatRecordDto chatRecord = chatRecordDtos.get(i);
                                //  自己的消息
                                if (NettyClientConstant.MsgUserType.Myself.getCode().equals(chatRecord.getMsgUserType())) {
                                    chat.addTalkMsgRight(chatRecord.getTalkId(), chatRecord.getMsgContent(), chatRecord.getMsgType(), chatRecord.getMsgDate(), true, false, false);
                                } else {
                                    // 好友的消息
                                    chat.addTalkMsgUserLeft(chatRecord.getTalkId(), null, null, chatRecord.getMsgContent(), chatRecord.getMsgType(), chatRecord.getMsgDate(), true, false, false);
                                }
                            }

                        }
                    }
                } catch (ParseException | URISyntaxException | IOException var24) {
                    var24.printStackTrace();
                } finally {
                    try {
                        if (httpClient != null) {
                            httpClient.close();
                        }

                        if (response != null) {
                            response.close();
                        }
                    } catch (IOException var23) {
                        var23.printStackTrace();
                    }
                }
            }
            // 寻找消息发送者对应的talkBox，将消息显示出来
            // 可能存在对应的talkBox以收起的情况，则需要展开该talkBox，
            chat.addTalkMsgUserLeft(msg.getSenderId(), msg.getSenderNickname(), msg.getSenderHead(), msg.getMsgText(), msg.getMsgType(), msg.getMsgDate(), true, false, true);
        });
    }
}
